@echo off
chcp 65001 > nul
setlocal enabledelayedexpansion

::登录uas
uas auth login --uos_app_id 23bef9e8-b862-49af-84ff-cde8446beeb2 --uos_app_secret fedd08f8098b43d78085d184605b96a6

:: 获取脚本所在目录
set "SCRIPT_DIR=%~dp0"
set "CONFIG_FILE=%SCRIPT_DIR%uos_sync_config.json"

echo ================================
echo      UOS文件夹同步工具
echo ================================
echo.

:: 检查配置文件是否存在
if not exist "%CONFIG_FILE%" (
    echo [错误] 配置文件不存在: %CONFIG_FILE%
    echo 请确保 uos_sync_config.json 文件在同一目录下
    pause
    exit /b 1
)

:: 检查uas.exe是否存在
if not exist "%SCRIPT_DIR%uas.exe" (
    echo [错误] UAS工具不存在: %SCRIPT_DIR%uas.exe
    echo 请确保 uas.exe 文件在同一目录下
    pause
    exit /b 1
)

echo [信息] 正在读取配置文件...

:: 使用临时PowerShell脚本文件读取JSON配置
set "TEMP_PS=%TEMP%\read_config.ps1"
echo $config = Get-Content -Path "%CONFIG_FILE%" -Encoding UTF8 ^| ConvertFrom-Json > "%TEMP_PS%"
echo Write-Output $config.bucket_id >> "%TEMP_PS%"
for /f "delims=" %%i in ('powershell -ExecutionPolicy Bypass -File "%TEMP_PS%"') do set "BUCKET_ID=%%i"

echo $config = Get-Content -Path "%CONFIG_FILE%" -Encoding UTF8 ^| ConvertFrom-Json > "%TEMP_PS%"
echo Write-Output $config.local_folder_path >> "%TEMP_PS%"
for /f "delims=" %%i in ('powershell -ExecutionPolicy Bypass -File "%TEMP_PS%"') do set "LOCAL_PATH=%%i"

echo $config = Get-Content -Path "%CONFIG_FILE%" -Encoding UTF8 ^| ConvertFrom-Json > "%TEMP_PS%"
echo Write-Output $config.remote_folder_name >> "%TEMP_PS%"
for /f "delims=" %%i in ('powershell -ExecutionPolicy Bypass -File "%TEMP_PS%"') do set "REMOTE_FOLDER=%%i"

:: 清理临时文件
if exist "%TEMP_PS%" del "%TEMP_PS%"

:: 验证配置参数
if "%BUCKET_ID%"=="" (
    echo [错误] 配置文件中缺少 bucket_id 参数
    pause
    exit /b 1
)

if "%LOCAL_PATH%"=="" (
    echo [错误] 配置文件中缺少 local_folder_path 参数
    pause
    exit /b 1
)

if "%REMOTE_FOLDER%"=="" (
    echo [错误] 配置文件中缺少 remote_folder_name 参数
    pause
    exit /b 1
)

:: 检查本地文件夹是否存在
if not exist "%LOCAL_PATH%" (
    echo [错误] 本地文件夹不存在: %LOCAL_PATH%
    echo 请检查配置文件中的路径设置
    pause
    exit /b 1
)

echo [配置信息]
echo   Bucket ID: %BUCKET_ID%
echo   本地路径: %LOCAL_PATH%
echo   远程文件夹: %REMOTE_FOLDER%
echo.

echo [确认] 即将开始同步操作，这将执行创建/更新/删除 Entry 三个操作
echo 按任意键继续，或关闭窗口取消...
pause > nul

echo.
echo [执行] 开始同步文件夹...
echo 命令: uas entries sync --bucket %BUCKET_ID% "%LOCAL_PATH%" "%REMOTE_FOLDER%"
echo.

:: 切换到uas.exe所在目录并执行同步命令
cd /d "%SCRIPT_DIR%"
uas.exe entries sync --bucket %BUCKET_ID% "%LOCAL_PATH%" "%REMOTE_FOLDER%"

:: 检查执行结果
if %ERRORLEVEL% EQU 0 (
    echo.
    echo [成功] 同步操作完成！
) else (
    echo.
    echo [失败] 同步操作失败，错误代码: %ERRORLEVEL%
    echo 请检查网络连接、认证信息和配置参数
)

echo.
echo 按任意键退出...
pause > nul